/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ifpe.dao;

import java.sql.PreparedStatement;
import ifpe.entities.Grupo;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 *
 * @author Sostenes
 */
public class GrupoDaoImpl extends Dao implements GrupoDao {

    @Override
    public void insert(Grupo grupo) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try {
            conn = getConnection();
            pstmt = conn.prepareStatement(
                    "insert into grupo (nome_grupo) values (?)");
            pstmt.setString(1, grupo.getNome());
            pstmt.executeUpdate();
            rs = pstmt.getGeneratedKeys();
            if (rs.next()) {
                grupo.setId(rs.getLong(1));
            }
        } catch (SQLException ex) {
            throw new DaoException(ex);
        } finally {
            try {
                if (rs != null) {
                    rs.close();
                }
            } catch (SQLException ex) {
                throw new DaoException(ex);
            }
            try {
                if (pstmt != null) {
                    pstmt.close();
                }
            } catch (SQLException ex) {
                throw new DaoException(ex);
            }
        }
    }

    @Override
    public Grupo get(Long id) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        Grupo grupo = null;
        try {
            conn = getConnection();
            pstmt = conn.prepareStatement(
                    "select id, nome_grupo from grupo where id = ?");
            pstmt.setLong(1, id);
            rs = pstmt.executeQuery();

            if (rs.next()) {
                grupo = new Grupo();
                grupo.setId(rs.getLong("id"));
                grupo.setNome(rs.getString("nome_grupo"));
            }

        } catch (SQLException ex) {
            throw new DaoException(ex);
        } finally {
            try {
                if (rs != null) {
                    rs.close();
                }
            } catch (SQLException ex) {
                throw new DaoException(ex);
            }
            try {
                if (pstmt != null) {
                    pstmt.close();
                }
            } catch (SQLException ex) {
                throw new DaoException(ex);
            }
        }
        return grupo;
    }
}
